print("上下文##################################################start")
from contextlib import contextmanager


# 很多时候，我们希望在某段代码执行前后自动执行特定代码，也可以用@contextmanager实现
# 如果一个对象没有实现上下文，我们就不能把它用于with语句
# with语句允许我们非常方便地使用资源，而不必担心资源没有关闭
class Query(object):

    def __init__(self, name):
        self.name = name

    def query(self):
        print('Query info about %s...' % self.name)


@contextmanager
def create_query(name):
    print('Begin')
    q = Query(name)
    yield q
    print('End')


with create_query('Bob') as q:
    q.query()


@contextmanager
def tag(name):
    print("<%s>" % name)
    yield
    print("</%s>" % name)


with tag("h1"):
    print("hello")
    print("world")
    print("world2")

# closing()来把该对象变为上下文对象
from contextlib import closing
from urllib.request import urlopen

with closing(urlopen('https://www.python.org')) as page:
    for line in page:
        print(line)

print("上下文##################################################end\n")
